//#include<bits/stdc++.h>
#include<iostream>
#include<list>
#include<string>
#include<vector>
using namespace std;
#define int long long
#define endl "\n"
#define x first
#define y second

const int INF = 0x3f,MOD = 1e9+7;

class dq {
//	list<vector<int>> que;
	vector<list<int>> que;
	int size = 1;
	
public:
	dq() {
		
	}
	void push_back(int a,int xx){
		
		que[a-1].push_back(xx);
	}
	void pop_back(int a){
//		que.
		que[a].pop_back();
	}
	void push_front(int a,int xx){
		que[a-1].pop_front(xx);
	}
	void pop_front(int a,int xx){
		que[a-1].pop_front(xx);
	}
	int size(int a){
		return que[a-1].size();
	}
	int back(int a){
		return que[a-1].back();
	}
	int front(int a){
		return que[a-1].front();
	}
};
signed main()
{
	int n ;
	dq dd;
	while(n --){
		string s;
		cin >> s ;
		int a ,b;
		
		if(s == "push_back"){
			cin >> a >> b;
			dd.push_back(a,b);
		}
		else if(s == "pop_back" ){
			cin >> a ;
			dd.pop_back(a);
		}else if( s == "push_front"){
			cin >> a >> b;
			dd.push_front(a,b);
		}else if(s == "pop_front"){
			cin >> a;
			dd.pop_front(a);
		}else if(s == "size"){
			cin >> a;
			cout << dd.size(a)<<endl;
		}else if(s == "back"){
			cin>> a;
			cout<< dd.back(a)<<endl;
		}else if( s == "front"){
			cin >> a;
			cout << dd.front(a)<<endl;
		}
	}
	return 0;
}
